import materialPng from './images/material-image.png';
import locationPng from './images/location.png';
import { backgroundColor, cesiumMapKeys } from '../../../utils/constant';
import FetchHelper from '../../../utils/helper/fetch-helper';
import Api, { GrasslandApi, HomeApi, YakApi } from '../../../utils/api';
import WKT from "terraformer-wkt-parser";
import { generateHtml, getDetail, getVectorDetail, yakPopup } from './mapUtils';
import { CesiumPopup } from './CesiumPopup';
import messageController from '../../../utils/messageController';

const Cesium = window.Cesium;
const turf = window.turf;

export default class CesiumMap {
    constructor(props) {
        Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMmZjMmYyZC1lZTkzLTQzYjctYmE2NS01NTQ0NzQyMWZhNDMiLCJpZCI6MTA2NjEsImlhdCI6MTYwNjI4NjY2MH0.PN1-x4vXpC68czogub9X0UDA3GaGE-31PZVbrRyI7CQ';

        let terrainProvider;
        if (props.tdtTerrainOpts) {
            const urls = []
            for (var i = 0; i < props.tdtTerrainOpts.subdomains.length; i++) {
                var url = props.tdtTerrainOpts.url.replace('{s}', props.tdtTerrainOpts.subdomains[i]);
                urls.push(url);
                terrainProvider = new Cesium.GeoTerrainProvider({
                    urls: urls
                })
            }
        } else {
            terrainProvider = new Cesium.CesiumTerrainProvider({
                url: props.terrainUrl || "/hongyuanxian"
            })
        }
        const viewer = this.viewer = window.vvv = new Cesium.Viewer(props.elementId || "map", {
            selectionIndicator: false,
            animation: false, //是否显示动画控件
            homeButton: false, //是否显示home键
            geocoder: false,// 查询
            baseLayerPicker: false, //是否显示图层选择控件
            timeline: false, //是否显示时间线控件
            fullscreenButton: false, //是否全屏显示
            scene3DOnly: true, //如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
            infoBox: false, //是否显示点击要素之后显示的信息
            sceneModePicker: false, //是否显示投影方式控件  三维/二维
            navigationHelpButton: false, //是否显示帮助信息控件
            // imageryProvider: new Cesium.UrlTemplateImageryProvider({
            //     url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
            // }),
            // imageryProvider: new Cesium.UrlTemplateImageryProvider({
            //     url: '/tile/anhui/{z}/{x}/{y}.png',
            // }),
            terrainProvider: terrainProvider,
            // terrainProvider: new Cesium.CesiumTerrainProvider({
            //     requestWaterMask: true,
            //     requestVertexNormals: true,
            //     isSct: false,
            //     url: "https://www.supermapol.com/realspace/services/3D-stk_terrain/rest/realspace/datas/info/data/path"
            // }),
            // terrainProvider: new Cesium.ArcGISTiledElevationTerrainProvider({
            //     url: 'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer',
            //     token: 'KED1aF_I4UzXOHy3BnhwyBHU4l5oY6rO6walkmHoYqGp4XyIWUd5YZUC1ZrLAzvV40pR6gBXQayh0eFA8m6vPg..'
            // }),
            skyAtmosphere: false,
            // orderIndependentTranslucency: false,
            contextOptions: {
                webgl: {
                    alpha: true,
                },
            },
            // terrainProvider: Cesium.createWorldTerrain(),
        });

        window.vvv.__getConfig = () => {
            const config = {
                "destination": window.vvv.camera.position,
                "orientation": {
                    "heading": window.vvv.camera.heading,
                    "pitch": window.vvv.camera.pitch,
                    "roll": window.vvv.camera.roll,
                }
            }
            return JSON.stringify(config, 2, null);
        }
        viewer.scene.globe.terrainExaggeration = 1.5;
        viewer.imageryLayers.removeAll()
        // viewer.scene.skyBox.destroy();
        // viewer.scene.skyBox = undefined;
        // viewer.scene.sun.destroy();
        // viewer.scene.sun = undefined;
        // viewer.scene.moon.destroy();
        // viewer.scene.moon = undefined;
        // viewer.scene.sun.show = false;
        // viewer.scene.moon.show = false;
        // viewer.scene.skyBox.show = false;
        viewer.scene.undergroundMode = false;
        viewer.scene.fxaa = true;
        viewer.scene.postProcessStages.fxaa.enabled = true;
        viewer._cesiumWidget._creditContainer.style.display = "none";
        viewer.scene.globe.baseColor = Cesium.Color.fromCssColorString(backgroundColor)// new Cesium.Color(0, 0, 0, 0);
        viewer.scene.backgroundcolor = Cesium.Color.fromCssColorString(backgroundColor);
        viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
        // viewer.scene.skyAtmosphere.show = false
        // viewer.scene.screenSpaceCameraController.minimumZoomDistance = props.minimumZoomDistance || 1000;
        viewer.scene.screenSpaceCameraController.maximumZoomDistance = props.maximumZoomDistance || 50000;
        viewer.scene.globe.depthTestAgainstTerrain = false

        viewer.camera.setView({
            // 设置相机位置
            destination: props.destination,
            orientation: props.orientation
        });
        const globe = viewer.scene.globe;
        // globe.translucency.frontFaceAlphaByDistance = new Cesium.NearFarScalar(
        //     400.0,
        //     0.0,
        //     800.0,
        //     1.0
        // );
        // globe.translucency.enabled = true;
        // globe.translucency.frontFaceAlphaByDistance.nearValue = Cesium.Math.clamp(
        //     0.3,
        //     0.0,
        //     0.1
        // );
        // globe.translucency.frontFaceAlphaByDistance.farValue = 1.0;

        let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction((event) => {
            this.clear(true);
            // this.viewer.entities.removeAll();
            var pickedFeature = viewer.scene.pick(event.position);

            const id = pickedFeature?.id?.properties?.id?.getValue();
            const detailHandler = pickedFeature?.id?.properties?.detailHandler?.getValue();
            let ray = viewer.camera.getPickRay(event.position);

            let cartesian = viewer.scene.globe.pick(ray, viewer.scene);
            let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
            let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
            let alt = cartographic.height; // 高度
            let coordinate = {
                longitude: Number(lng.toFixed(6)),
                latitude: Number(lat.toFixed(6)),
                altitude: Number(alt.toFixed(2))
            };

            const cartesian33 = Cesium.Cartesian3.fromDegrees(coordinate.longitude, coordinate.latitude, coordinate.altitude)
            const html = `<div id="info-popup"></div>`

            const showPopup = (tabs, detail, resultData) => {
                if (tabs?.length > 0) {
                    if (!this.popup) {
                        this.popup = new CesiumPopup(viewer, {
                            position: cartesian33, html: html, className: "info-popup", popPosition: "leftbottom",
                            style: {
                                ...detail?.popupProps,
                                width: (detail?.popupProps?.width || 270) + 'px',
                            }
                        }, {})
                    }
                    this.popup.setContent(html);
                    this.popup.setPosition(cartesian33);
                    this.popup?.show();
                    generateHtml('info-popup', tabs, resultData)
                    messageController.emit(cesiumMapKeys.featureClick, {
                        tabs, detail, resultData
                    })
                }
                else {
                    messageController.emit(cesiumMapKeys.featureClick, null)
                    this.popup?.remove();
                    this.popup = null;
                }
            }
            if (detailHandler) {
                detailHandler().then(resp => {
                    const { layerOpt } = resp;
                    if (layerOpt) {
                        if (layerOpt.detail) {
                            const { url, mapping } = layerOpt.detail;
                            const tabs = [];
                            let geom;
                            mapping?.forEach(item => {
                                let dataItem = resp?.data;
                                if (item.field) {
                                    dataItem = resp?.data?.[item.field];
                                }
                                if (dataItem?.geom) {
                                    geom = dataItem?.geom;
                                }
                                if (dataItem?.id) {
                                    tabs.push({
                                        ...dataItem,
                                        title: item.title,
                                        dyColumn: dataItem?.dyColumn,
                                        geom: dataItem?.geom
                                    })
                                } else if (dataItem?.data?.length > 0) {
                                    if (item.type === 'echarts') {
                                        tabs.push({
                                            option: {
                                                color: [
                                                    '#44B7D3',
                                                    '#E42B6D',
                                                    '#F4E24E',
                                                    '#FE9616',
                                                    '#8AED35',
                                                    '#ff69b4',
                                                    '#ba55d3',
                                                    '#cd5c5c',
                                                    '#ffa500',
                                                    '#40e0d0',
                                                    '#E95569',
                                                    '#ff6347',
                                                    '#7b68ee',
                                                    '#00fa9a',
                                                    '#ffd700',
                                                    '#6699FF',
                                                    '#ff6666',
                                                    '#3cb371',
                                                    '#b8860b',
                                                    '#30e0e0'
                                                ],
                                                legend: {
                                                    ...item.chartOptions?.legend,
                                                    data: dataItem?.legend
                                                },
                                                tooltip: {
                                                    ...item.chartOptions?.tooltip
                                                },
                                                series: [
                                                    {
                                                        name: item.title,
                                                        type: item.chartOptions.chartType,
                                                        radius: '50%',
                                                        data: dataItem?.data,
                                                    }
                                                ]
                                            },
                                            ...item
                                        })
                                    }
                                } else if (dataItem?.dyColumn) {
                                    tabs.push({
                                        ...dataItem,
                                        title: item.title,
                                        dyColumn: dataItem?.dyColumn
                                    })
                                }
                            })
                            showPopup(tabs, layerOpt.detail, resp.data);
                        }
                    }
                })
            } else if (id) {
                getVectorDetail(this, props.layers.filter(l => l.layerType === 'vector'), id).then(({ tabs, detail, resultData }) => {
                    showPopup(tabs, detail, resultData);
                    this.highlightWkts([pickedFeature.id.properties.wkt.getValue()]);
                }).catch(err => {
                    this.popup?.remove();
                    this.popup = null;
                });
            } else {
                getDetail(this, props.layers.filter(l => l.layerType !== 'vector'), `POINT(${coordinate.longitude} ${coordinate.latitude})`).then(({ tabs, detail, resultData, geom }) => {
                    showPopup(tabs, detail, resultData);
                    const geom2 = geom || tabs.find(tab => {
                        return tab.geom;
                    })?.geom;
                    if (geom2) {
                        this.highlightWkts([geom2]);
                    }
                }).catch(err => {
                    this.popup?.remove();
                    this.popup = null;
                });
            }
            // console.log(pickedFeature)

            // console.log(coordinate);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
    clear(notRemoveHigh) {
        const viewer = this.viewer;
        !notRemoveHigh && this.highlightIds?.forEach(id => {
            viewer.entities.removeById(id);
        })
        if (this.lastPointId && !notRemoveHigh) {
            viewer.entities.removeById(this.lastPointId);
        }
        if (this.lastLocationId) {
            viewer.entities.removeById(this.lastLocationId);
        }
        if (this.popup) {
            this.popup?.remove();
            this.popup = null;
        }
        // this.removeAiResult()
    }
    clipByGeo(rootGeo, callback) {
        const viewer = this.viewer;

        // const maskpointArray = [], bounds = [];
        // const coordinates = rootGeo.geometry.coordinates;
        // for (let i = 0; i < coordinates.length; i++) {
        //     bounds.push([coordinates[i][0], coordinates[i][1],]);
        //     maskpointArray.push(coordinates[i][0]);
        //     maskpointArray.push(coordinates[i][1]);
        //     // maskpointArray.push(10000);
        // }
        // var maskspoint = Cesium.Cartesian3.fromDegreesArray(maskpointArray);
        // const boundspolygon = turf.polygon([bounds]);
        // const extent = turf.bbox(boundspolygon)

        // const entity1 = new Cesium.Entity({
        //     id: 1,
        //     name: 'Blue box',
        //     // position: Cesium.Cartesian3.fromDegrees(115.508632, 32.468565),
        //     // box: {
        //     //   dimensions: new Cesium.Cartesian3(1000.0, 1000.00, 50000.0),
        //     //   material: Cesium.Color.GREEN
        //     // },
        //     polygon: {
        //         // height: 0,
        //         // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         // extrudedHeight: 0,
        //         // extrudedHeightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         hierarchy: { // 绘制的区域太大容易卡顿
        //             positions: Cesium.Cartesian3.fromDegreesArray([ // 100, 0, 100, 89, 150, 89, 150, 0,
        //                 // 113.37890625, 37.50972584293751, 121.28906250000001, 37.50972584293751, 121.28906250000001, 42.35854391749705,
        //                 // 113.37890625, 42.35854391749705, 113.37890625, 37.50972584293751,
        //                 // extent[0],
        //                 // extent[1],
        //                 // extent[0],
        //                 // extent[3],
        //                 // extent[2],
        //                 // extent[1],
        //                 // extent[2],
        //                 // extent[3],
        //                 // extent[0],
        //                 // extent[1],
        //                 135,
        //                 3,
        //                 135,
        //                 53,
        //                 73,
        //                 53,
        //                 73,
        //                 3,
        //                 135,
        //                 3,
        //             ]), // holes是图形内需要挖空的区域
        //             holes: [{
        //                 positions: maskspoint,
        //             }],
        //         },
        //         // material: new Cesium.ImageMaterialProperty({
        //         //     image: '/cxph-jgpt/images/background.png',
        //         //     repeat: new Cesium.Cartesian2(4, 4)
        //         // })
        //         // material: Cesium.Color.fromCssColorString("#6dcdeb"),
        //         material: Cesium.Color.fromCssColorString(backgroundColor), // material:Cesium.Color.WHITE.withAlpha(1),
        //     },
        // });
        // const entity2 = new Cesium.Entity({
        //     id: 2,
        //     name: 'Blue box2',
        //     // position: Cesium.Cartesian3.fromDegrees(115.508632, 32.468565),
        //     // box: {
        //     //   dimensions: new Cesium.Cartesian3(1000.0, 1000.00, 50000.0),
        //     //   material: Cesium.Color.GREEN
        //     // },
        //     polygon: {
        //         height: -10000,
        //         // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         extrudedHeight: -10000,
        //         // extrudedHeightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         hierarchy: { // 绘制的区域太大容易卡顿
        //             positions: maskspoint, // holes是图形内需要挖空的区域

        //         },
        //         // material: new Cesium.ImageMaterialProperty({
        //         //     image: '/cxph-jgpt/images/background.png',
        //         //     repeat: new Cesium.Cartesian2(4, 4)
        //         // })
        //         material: Cesium.Color.fromCssColorString("#ffff00"),
        //         // material: Cesium.Color.fromCssColorString("#041320"), // material:Cesium.Color.WHITE.withAlpha(1),
        //     },
        // });
        // const entity = this.wallEntity = new Cesium.Entity({
        //     name: "动态立体墙",
        //     wall: {
        //         positions: maskspoint,
        //         maximumHeights: maskspoint.map((res) => {
        //             return 6000;
        //         }),
        //         minimumHeights: maskspoint.map((res) => {
        //             return -6000;
        //         }),
        //         heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         material: new Cesium.ImageMaterialProperty({
        //             image: materialPng,
        //             transparent: true,
        //             // repeat: new Cesium.Cartesian2(4, 4),
        //             color: Cesium.Color.fromCssColorString("rgba(0,255,255,0.6)")//"rgba(0,255,255,0.6)"
        //         })
        //         // material: Cesium.Color.fromCssColorString("rgba(0,255,255,0.6)"),
        //     },
        // });
        // viewer.entities.add(entity1);
        // viewer.entities.add(entity2);
        // viewer.entities.add(entity);
        // viewer.flyTo(entity, {
        //     duration: 3,
        // });
        callback && callback(viewer);
    }
    flyToByWkt(wkt, detail, opt) {
        const geojson = this.geoJsonFromWkt(wkt);
        console.log(geojson)
        if (geojson.type === 'Point') {
            this.flyToByPoint(geojson.coordinates, detail, opt);
            return
        }
        var coordinates = geojson.coordinates;

        let center;
        if (geojson.type === 'MultiPolygon') {
            const mp = turf.multiPolygon(coordinates);

            center = turf.pointOnFeature(mp).geometry.coordinates;
            // var polygonArr = geojson.coordinates.toString().split(',').filter(v => {
            //     return v !== '0'
            // });
        } else {
            // const center = f.properties.center.replace('POINT(', '').replace(')', '').split(' ');
            const polygon = turf.polygon(coordinates);

            center = turf.pointOnFeature(polygon).geometry.coordinates;

            // var polygonArr = geojson.coordinates.toString().split(',').filter(v => {
            //     return v !== '0'
            // });
        }
        if (center) {
            this.flyToByPoint(center, detail, opt);
        }
        // const entity = new Cesium.Entity({
        //     id: Math.random().toString(),
        //     name: '2 box',
        //     // position: Cesium.Cartesian3.fromDegrees(115.508632, 32.468565),
        //     // box: {
        //     //   dimensions: new Cesium.Cartesian3(1000.0, 1000.00, 50000.0),
        //     //   material: Cesium.Color.GREEN
        //     // },
        //     // clampToGround: false,
        //     polygon: {
        //         // clampToGround: false,
        //         // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
        //         // height: 0,
        //         // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         // extrudedHeight: 0,
        //         // extrudedHeightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //         hierarchy: { // 绘制的区域太大容易卡顿
        //             positions: Cesium.Cartesian3.fromDegreesArray(polygonArr)
        //         },
        //         outline: true,
        //         outlineColor: Cesium.Color.RED,//fromCssColorString("#f00"),
        //         outlineWidth: 12,
        //         material: Cesium.Color.fromCssColorString("#ff0").withAlpha(0.0), // material:Cesium.Color.WHITE.withAlpha(1),
        //     },
        // });
        // this.viewer.entities.add(entity);
        // this.viewer.flyTo(entity, {
        //     duration: 3,
        //     // offset: new Cesium.HeadingPitchRange(6.261543600899495, -1.0915197083635215, 2000)
        // });
    }
    highlightWkts(wkts, autoFlyto, attrs) {
        if (!this.highlightIds) {
            this.highlightIds = [];
        }
        this.highlightIds.forEach(id => {
            this.viewer.entities.removeById(id);
        })

        // this.viewer.scene.globe.terrainExaggeration = 1.5;
        wkts.forEach((wkt, i) => {
            const geojson = this.geoJsonFromWkt(wkt);
            if (geojson.type === 'Point') {
                const id = this.lastPointId = Math.random().toString().substring(3)
                this.highlightIds.push(id);
                const coordinates = geojson.coordinates;
                coordinates[0] = Math.round(coordinates[0] * 100000) / 100000
                coordinates[1] = Math.round(coordinates[1] * 100000) / 100000

                let entity = this.viewer.entities.add({
                    id: id,
                    name: "highlight-point",
                    position: Cesium.Cartesian3.fromDegrees(...coordinates), //经纬度转世界坐标
                    point: {
                        show: true,
                        color: Cesium.Color.fromCssColorString("#00ff00").withAlpha(.5),
                        pixelSize: 16,
                        outlineColor: Cesium.Color.fromCssColorString("#00ffff"),
                        outlineWidth: 2,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        // material: new Cesium.ImageMaterialProperty({
                        //     image: locationPng,
                        //     repeat: new Cesium.Cartesian2(4, 4)
                        // })
                    }
                });
                entity.properties = attrs?.[i]
                autoFlyto && this.viewer.flyTo(entity, {
                    duration: 3,
                    // offset: new Cesium.HeadingPitchRange(6.261543600899495, -1.0915197083635215, 2000)
                })
            } else if (geojson.type === 'Polygon') {
                const id = this.lastPointId = Math.random().toString().substring(3)
                this.highlightIds.push(id);
                this.highlightIds.push(id + 'polyline');
                const polygonArr = geojson.coordinates.toString().split(',').filter(v => {
                    return v !== '0'
                });

                var coordinates = geojson.coordinates;
                const polygon = turf.polygon(coordinates);

                const center = turf.pointOnFeature(polygon).geometry.coordinates;
                const positions = Cesium.Cartesian3.fromDegreesArray(polygonArr);
                const polyline = this.viewer.entities.add({
                    id: id,
                    name: '',
                    polygon: {
                        hierarchy: Cesium.Cartesian3.fromDegreesArray(polygonArr),
                        // width: 5,
                        clampToGround: true,
                        material: Cesium.Color.RED.withAlpha(0),
                    }
                })
                polyline.properties = attrs?.[i]
                this.viewer.entities.add({
                    id: id + 'polyline',
                    name: '',
                    polyline: {
                        positions: positions,
                        width: 5,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        clampToGround: true,
                        material: Cesium.Color.YELLOW,
                    }
                })
                autoFlyto && this.viewer.flyTo(polyline, {
                    duration: 3,
                    // offset: new Cesium.HeadingPitchRange(6.261543600899495, -1.0915197083635215, 2000)
                })
                // 获取多边形的边界坐标
                // var positions2 = polyline.polyline.hierarchy.getValue(Cesium.JulianDate.now()).positions;
                // console.log(positions, positions2)
                // 计算适当的缩放级别和中心点
                // var boundingSphere = Cesium.BoundingSphere.fromPoints(positions);
                // // var center = boundingSphere.center;
                // var radius = boundingSphere.radius;

                // var zoomFactor = 0.5; // 缩放因子，可以根据需要进行调整
                // var desiredZoomLevel = (Cesium.Math.toDegrees(this.viewer.camera.frustum.fovy) / 2) * zoomFactor;
                // var distance = radius / Math.tan(Cesium.Math.toRadians(desiredZoomLevel));
                // var destination = Cesium.Cartesian3.fromDegrees(center[0], center[1], distance);

                // 设置缩放级别和相机位置
                // this.viewer.camera.setView({
                //     destination: destination,
                //     orientation: {
                //         heading: this.viewer.camera.heading,
                //         pitch: this.viewer.camera.pitch,
                //         roll:  this.viewer.camera.roll,
                //     }
                // });
            } else if (geojson.type === 'MultiPolygon') {
                let entity;
                geojson.coordinates.forEach(c => {
                    c.forEach(cs => {
                        const id = this.lastPointId = Math.random().toString().substring(3)
                        this.highlightIds.push(id);
                        this.highlightIds.push(id + 'polyline');
                        const polygonArr = cs.toString().split(',').filter(v => {
                            return v !== '0'
                        });
                        entity = this.viewer.entities.add({
                            id: id,
                            name: '',
                            polygon: {
                                hierarchy: Cesium.Cartesian3.fromDegreesArray(polygonArr),
                                // width: 5,
                                clampToGround: true,
                                material: Cesium.Color.RED.withAlpha(0),
                            }
                        })

                        entity.properties = attrs?.[i]
                        this.viewer.entities.add({
                            id: id + 'polyline',
                            name: '',
                            polyline: {
                                positions: Cesium.Cartesian3.fromDegreesArray(polygonArr),
                                width: 5,
                                clampToGround: true,
                                material: Cesium.Color.YELLOW,
                            }
                        })
                    })
                })
                autoFlyto && entity && this.viewer.flyTo(entity, {
                    duration: 3,
                    // offset: new Cesium.HeadingPitchRange(6.261543600899495, -1.0915197083635215, 2000)
                })
            }
        })
    }
    flyToByPoint(point, detail, opts = {}) {
        const { png, hideLocation } = opts;
        if (this.lastLocationId) {
            this.viewer.entities.removeById(this.lastLocationId);
            // this.viewer.entities.removeAll();
        }
        const id = this.lastLocationId = Math.random().toString().substring(3)
        let entity = this.viewer.entities.add({
            id: id,
            name: "点",
            position: Cesium.Cartesian3.fromDegrees(...point), //经纬度转世界坐标
            // point: {
            //     show: true,
            //     color: Cesium.Color.GREEN,
            //     pixelSize: 20,
            //     outlineColor: Cesium.Color.YELLOW,
            //     outlineWidth: 3,
            //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            //     // material: new Cesium.ImageMaterialProperty({
            //     //     image: locationPng,
            //     //     repeat: new Cesium.Cartesian2(4, 4)
            //     // })
            // },
            billboard: new Cesium.BillboardGraphics({
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                image: png || locationPng,
                pixelOffset: new Cesium.Cartesian2(0, -16),
                // color: Cesium.Color.YELLOW,
                scale: hideLocation ? 0.0001 : 1
            })
        });
        // entity.billboard = new Cesium.BillboardGraphics({
        //     image: locationPng
        // });
        this.viewer.flyTo(entity, {
            duration: 3,
            offset: new Cesium.HeadingPitchRange(6.261543600899495, -1.0915197083635215, window.globalConfig.rangeWhenNav || 10000)
        }).then(r => {
            var cartographic = Cesium.Cartographic.fromCartesian(entity.position.getValue());
            var lon = Cesium.Math.toDegrees(cartographic.longitude);
            var lat = Cesium.Math.toDegrees(cartographic.latitude);
            var altitude = this.viewer.scene.globe.getHeight(cartographic);

            if (detail) {
                const html = `<div id="info-popup"></div>`
                const cartesian33 = Cesium.Cartesian3.fromDegrees(lon, lat, altitude)
                if (!this.popup) {
                    this.popup = new CesiumPopup(this.viewer, {
                        position: cartesian33, html: html, className: "info-popup", popPosition: "leftbottom"
                    }, {})
                }
                this.popup.setContent(html);
                this.popup.setPosition(cartesian33);
                this.popup?.show();
                generateHtml('info-popup', detail)
            }
        });
        // this.viewer.camera.flyTo({
        //     destination: Cesium.Cartesian3.fromDegrees(point[0], point[1], 100000),
        //     orientation: {
        //         heading: 6.261543600899495, // 水平偏角，默认正北 0
        //         pitch: -1.0915197083635215, // 俯视角，默认-90，垂直向下
        //         roll: 6.283184800621125, // 旋转角
        //     },
        // });
    }
    createGroundPolylineGeometryInstance = (feature, options = {}) => {

        if (!feature) {
            return;
        }

        if (feature.geometry == null) {
            return;
        }

        var polygonArr = feature.geometry.coordinates.toString().split(',');
        var obj = new Cesium.GroundPolylineGeometry({
            positions: Cesium.Cartesian3.fromDegreesArray(polygonArr),
            loop: options.loop || true,
            width: options.width || 3.0,
        });

        return new Cesium.GeometryInstance({
            geometry: obj,
            attributes: {
                show: new Cesium.ShowGeometryInstanceAttribute(),
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(
                    Cesium.Color.fromCssColorString(options.color || "#17E6FF").withAlpha(0.7)
                ),
            },
        });
    }

    createGeometryInstances(features, color, ops = {}) {

        if (!features) {
            return;
        }
        var instances = [];

        for (let i = 0; i < features.length; i++) {
            for (let j = 0; j < features[i].geometry.coordinates.length; j++) {
                var feature = features[i];

                var polygonArr = feature.geometry.coordinates[0][j].toString().split(',');
                var polygon = new Cesium.PolygonGeometry({
                    polygonHierarchy: new Cesium.PolygonHierarchy(
                        Cesium.Cartesian3.fromDegreesArray(polygonArr)
                    ),
                    vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT
                });

                var properties = feature.properties;

                instances.push(new Cesium.GeometryInstance({
                    id: properties.code,
                    geometry: polygon,
                    attributes: {
                        color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString(color || "#6FA033")),//Cesium.Color.AQUAMARINE
                    },
                }));
            }
        }

        return instances;

    }

    getCenterFromCoordinates(coordinates) {
        var array = coordinates.toString().split(',')
        var positions = Cesium.Cartesian3.fromDegreesArray(array)
        return this.getPolygonCenter(positions);
    }

    getPolygonCenter(positions) {
        var poly = Cesium.BoundingSphere.fromPoints(positions);
        var cartographic = Cesium.Cartographic.fromCartesian(poly.center)

        var lat = Cesium.Math.toDegrees(cartographic.latitude);
        var long = Cesium.Math.toDegrees(cartographic.longitude);

        return { latitude: lat, longitude: long }
    }
    createLabel(position, text, options) {

        return {
            show: options.show,
            position: position,
            text: text || "",
            font: "normal 12px MicroSoft YaHei",
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            outlineWidth: 4,
            // font: "24px Helvetica", // 字体样式
            // fillColor: Cesium.Color.ORANGE, // 字体颜色
            // scaleByDistance: new Cesium.NearFarScalar(1.5e2, 2, 8.0e6, 0.1), // 重要：相机远近距离的
            // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
            // scale: 0.25,
            // showBackground: options.showBackground || true,
            // backgroundColor: options.backgroundColor || new Cesium.Color(0, 0, 0, 0),
            // backgroundPadding: options.backgroundPadding || new Cesium.Cartesian2(20, 20),
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            // pixelOffset: new Cesium.Cartesian2(1200, 0),
            //设置透明度
            // translucencyByDistance: options.translucencyByDistance || new Cesium.NearFarScalar(
            //     2000,
            //     1.0,
            //     88000,
            //     0.0
            // )
        };
    }

    removeAiResult() {
        this.aiResults?.forEach(id => {
            this.viewer.entities.removeById(id);
        })
    }
    addAiPolyline(features) {
        // const viewer = this.viewer;
        if (features.length === 0) {
            return;
        }

        // this.viewer.scene.globe.terrainExaggeration = 1.5;
        features.forEach(feature => {
            const polygonArr = feature.geometry.coordinates.toString().split(',').filter(v => {
                return v !== '0'
            });
            const id = 'ai-' + Math.random().toString().substring(3)
            if (!this.aiResults) {
                this.aiResults = [];
            }
            this.aiResults.push(id);
            this.viewer.entities.add({
                id: id,
                name: '',
                polyline: {
                    positions: Cesium.Cartesian3.fromDegreesArray(polygonArr),
                    width: 5,
                    clampToGround: true,
                    // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    material: Cesium.Color.RED
                }
            })
        })
        //     geometryInstances: instances,
        //     appearance: new Cesium.PerInstanceColorAppearance({ // 为每个instance着色
        //         translucent: true,
        //         closed: false
        //     }),
        //     show: true,
        //     classificationType: Cesium.ClassificationType.BOTH,//BOTH,//CESIUM_3D_TILE
        // });

        // primitive.name = "ai-primitives";
        // this.viewer.scene.primitives.add(primitive);
        // viewer.scene.primitives.add(this.labelPrimitives);
    }
    addPolyline(features) {
        const viewer = this.viewer;
        if (features.length === 0) {
            return;
        }
        if (!this.labelPrimitives) {
            this.labelPrimitives = new Cesium.LabelCollection();
            this.labelPrimitives.name = "xzdy.label";
        }
        const instances = features.forEach(f => {
            var coordinates = f.geometry.coordinates;

            // const center = f.properties.center.replace('POINT(', '').replace(')', '').split(' ');
            var polygon = turf.polygon(coordinates);
            var center = turf.centerOfMass(polygon).geometry.coordinates;
            // if(f.properties.center){
            //     center = this.geoJsonFromWkt(f.properties.center).coordinates;
            // }
            console.log(center)
            // let pointCenter = this.getCenterFromCoordinates(coordinates);
            var position = Cesium.Cartesian3.fromDegrees(center[0], center[1])
            // let label = this.createLabel(position, f.properties.name,
            //     {
            //         show: true,
            //     });
            // this.labelPrimitives.add(label);
            viewer.entities.add({
                position: position,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                label: {
                    font: "normal 18px MicroSoft YaHei",
                    clampToGround: true,
                    text: f.properties.name,
                    fillColor: Cesium.Color.WHITE,
                    outlineColor: Cesium.Color.BLACK,
                    outlineWidth: 4,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                },
            });
            // const polygonArr = f.geometry.coordinates.toString().split(',').filter(v => {
            //     return v !== '0'
            // });
            // const id = 'zone-' + Math.random().toString().substring(3)
            // this.viewer.entities.add({
            //     id: id,
            //     name: '',
            //     polyline: {
            //         positions: Cesium.Cartesian3.fromDegreesArray(polygonArr),
            //         width: 5,
            //         clampToGround: true,
            //         // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            //         material: Cesium.Color.BLUE
            //     }
            // })
            // return this.createGroundPolylineGeometryInstance(f);
        })
        // viewer.scene.primitives.add(this.labelPrimitives);
    }
    addPolygon(features, options = {}) {
        const viewer = this.viewer;
        if (features.length === 0) {
            return;
        }
        const instances = this.createGeometryInstances(features, options.color || "#fff");

        const primitive = new Cesium.GroundPrimitive({//Primitive
            geometryInstances: instances,
            appearance: new Cesium.PerInstanceColorAppearance({ // 为每个instance着色
                translucent: true,
                closed: false
            }),
            show: true,
            classificationType: Cesium.ClassificationType.BOTH,//BOTH,//CESIUM_3D_TILE
        });

        primitive.name = "polygon-primitives";
        viewer.scene.primitives.add(primitive);
    }
    loadZoneJson(url) {
        Api.getSubZone().then(data => {
            this.addPolyline(data.features);
            this.zoneFeatures = data.features;
        })
    }
    geojsonToWkt(geojson) {
        return WKT.convert(geojson.geometry);
    }
    geoJsonFromWkt(wkt) {
        return WKT.parse(wkt)
    }
    getGeoJsonFromWkt(data) {
        var geoJson = { type: "FeatureCollection" };
        geoJson.features = data.filter(t => {
            return t.wkt;
        }).map(t => {
            var geo = this.geoJsonFromWkt(t.wkt);
            return {
                type: "Feature", geometry: { ...geo }, properties: {
                    ...t
                }
            }
        });
        return geoJson;

    }
    addGeoserverLayer(layerName, extent, isWms, includeLayers = true, layerOpt) {
        let layer;
        if (isWms) {
            let imageryProvider = new Cesium.WebMapServiceImageryProvider({
                url: '/geoserver/ne/wms',
                layers: layerName,
                tileWidth: 256,
                tileHeight: 256,
                enablePickFeatures: false,
                parameters: { transparent: true, format: 'image/png' },
                version: '1.1.0'
            });

            layer = this.viewer.imageryLayers.addImageryProvider(imageryProvider);
        } else {
            const geoserverOptions = this.geoserverOptions;
            let matrixIds = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10',
                'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19', 'EPSG:4326:20', 'EPSG:4326:21'];
            var wmtsImageryProvider = new Cesium.WebMapTileServiceImageryProvider({
                url: (geoserverOptions?.urlTemplate || '') + '/geoserver/gwc/service/wmts',
                layer: layerName,
                style: '',
                format: 'image/png',
                tileMatrixSetID: 'EPSG:4326',
                rectangle: Cesium.Rectangle.fromDegrees(...extent),
                tileMatrixLabels: matrixIds,
                tilingScheme: new Cesium.GeographicTilingScheme({
                    numberOfLevelZeroTilesX: 2,
                    numberOfLevelZeroTilesY: 1
                }),
                subdomains: geoserverOptions?.subdomains || []
            });
            layer = this.viewer.imageryLayers.addImageryProvider(wmtsImageryProvider);
        }
        if (includeLayers) {
            layer.show = false;
            if (!this.layers) {
                this.layers = [];
            }
            this.layers.push({
                layerName,
                layer: layer,
                legends: layerOpt?.legends
            })
        }
        return layer;
    }
}
